package com.schoolhelper.social.controller;

import com.schoolhelper.social.domain.Friendship;
import com.schoolhelper.social.dto.FriendRequestDTO;
import com.schoolhelper.social.dto.FriendDTO;
import com.schoolhelper.social.service.FriendshipService;
import com.schoolhelper.utils.Result;
import com.schoolhelper.config.FileUploadConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/friends")
@CrossOrigin(origins = "http://localhost:8080")
public class FriendshipController {
    
    private static final Logger logger = LoggerFactory.getLogger(FriendshipController.class);
    
    @Autowired
    private FriendshipService friendshipService;
    
    @Autowired
    private FileUploadConfig fileUploadConfig;
    
    /**
     * 发送好友请求
     */
    @PostMapping("/add")
    public Result<String> addFriend(@RequestBody Map<String, Object> request) {
        try {
            // 获取当前登录用户
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }
            
            Long friendId = Long.valueOf(request.get("friendId").toString());
            String remark = (String) request.get("remark");
            
            logger.info("发送好友请求: userId={}, friendId={}, remark={}", currentUserId, friendId, remark);
            
            boolean success = friendshipService.sendFriendRequest(currentUserId, friendId, remark);
            if (success) {
                return Result.success("好友请求发送成功");
            } else {
                return Result.error("好友请求发送失败，可能已经是好友或已发送过请求");
            }
        } catch (Exception e) {
            logger.error("发送好友请求失败", e);
            return Result.error("发送好友请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理好友请求
     */
    @PostMapping("/handle")
    public Result<String> handleFriendRequest(@RequestBody Map<String, Object> request) {
        try {
            Long requestId = Long.valueOf(request.get("requestId").toString());
            Boolean accept = (Boolean) request.get("accept");
            
            logger.info("处理好友请求: requestId={}, accept={}", requestId, accept);
            
            boolean success = friendshipService.handleFriendRequest(requestId, accept);
            if (success) {
                String message = accept ? "已同意好友请求" : "已拒绝好友请求";
                return Result.success(message);
            } else {
                return Result.error("处理好友请求失败");
            }
        } catch (Exception e) {
            logger.error("处理好友请求失败", e);
            return Result.error("处理好友请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取好友列表
     */
    @GetMapping("/list")
    public Result<List<FriendDTO>> getFriendList() {
        try {
            Long currentUserId = getCurrentUserId();
            logger.info("获取好友列表请求: currentUserId={}", currentUserId);
            
            if (currentUserId == null) {
                logger.warn("用户未登录，无法获取好友列表");
                return Result.error("用户未登录");
            }
            
            List<FriendDTO> friends = friendshipService.getUserFriends(currentUserId);
            logger.info("好友服务返回结果: friends={}", friends != null ? friends.size() : "null");
            
            // 处理好友头像URL
            if (friends != null) {
                for (FriendDTO friend : friends) {
                    if (friend.getAvatar() != null && !friend.getAvatar().isEmpty() && !friend.getAvatar().startsWith("http")) {
                        friend.setAvatar(fileUploadConfig.getFileUrl(friend.getAvatar()));
                    }
                }
            }
            
            logger.info("返回好友列表: size={}", friends != null ? friends.size() : 0);
            return Result.success(friends);
        } catch (Exception e) {
            logger.error("获取好友列表失败", e);
            return Result.error("获取好友列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取待确认的好友请求
     */
    @GetMapping("/requests/pending")
    public Result<List<FriendRequestDTO>> getPendingRequests() {
        try {
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }
            
            List<FriendRequestDTO> requests = friendshipService.getPendingRequests(currentUserId);
            
            // 处理好友请求中的头像URL
            for (FriendRequestDTO request : requests) {
                if (request.getAvatar() != null && !request.getAvatar().isEmpty() && !request.getAvatar().startsWith("http")) {
                    request.setAvatar(fileUploadConfig.getFileUrl(request.getAvatar()));
                }
            }
            
            return Result.success(requests);
        } catch (Exception e) {
            logger.error("获取待确认好友请求失败", e);
            return Result.error("获取待确认好友请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取发出的好友请求
     */
    @GetMapping("/requests/sent")
    public Result<List<Friendship>> getSentRequests() {
        try {
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }
            
            List<Friendship> requests = friendshipService.getSentRequests(currentUserId);
            return Result.success(requests);
        } catch (Exception e) {
            logger.error("获取发出的好友请求失败", e);
            return Result.error("获取发出的好友请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除好友
     */
    @DeleteMapping("/{friendId}")
    public Result<String> deleteFriend(@PathVariable Long friendId) {
        try {
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = friendshipService.deleteFriend(currentUserId, friendId);
            if (success) {
                return Result.success("删除好友成功");
            } else {
                return Result.error("删除好友失败");
            }
        } catch (Exception e) {
            logger.error("删除好友失败", e);
            return Result.error("删除好友失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查是否为好友关系
     */
    @GetMapping("/check/{friendId}")
    public Result<Boolean> checkFriendship(@PathVariable Long friendId) {
        try {
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }
            
            boolean isFriend = friendshipService.isFriend(currentUserId, friendId);
            return Result.success(isFriend);
        } catch (Exception e) {
            logger.error("检查好友关系失败", e);
            return Result.error("检查好友关系失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新好友备注
     */
    @PutMapping("/remark/{friendId}")
    public Result<String> updateFriendRemark(@PathVariable Long friendId, @RequestBody Map<String, String> request) {
        try {
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }
            
            String remark = request.get("remark");
            boolean success = friendshipService.updateFriendRemark(currentUserId, friendId, remark);
            if (success) {
                return Result.success("备注更新成功");
            } else {
                return Result.error("备注更新失败");
            }
        } catch (Exception e) {
            logger.error("更新好友备注失败", e);
            return Result.error("更新好友备注失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
                UserDetails userDetails = (UserDetails) authentication.getPrincipal();
                return Long.valueOf(userDetails.getUsername());
            }
            return null;
        } catch (Exception e) {
            logger.error("获取当前用户ID失败", e);
            return null;
        }
    }
}